package cn.vcjf.washcar.api.user.service.impl;

import cn.vcjf.washcar.api.user.entity.User;
import cn.vcjf.washcar.api.user.mapper.UserMapper;
import cn.vcjf.washcar.api.user.service.UserService;
import cn.vcjf.washcar.common.exception.ServiceException;
import cn.vcjf.washcar.common.util.JWT;
import cn.vcjf.washcar.common.util.QiniuUploadFile;
import cn.vcjf.washcar.common.web.TableResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qiniu.util.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-07-20
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Override
	public User getUserByOpenId(String openId) {
		return baseMapper.getUserByOpenId(openId);
	}

	@Override
	@Transactional(readOnly = false)
	public TableResult getTokenByOpenId(String openId,User userInfo) {
		TableResult result = TableResult.Result();
		try {
			//先到数据库验证
			User user = baseMapper.getUserByOpenId(openId);
			//非第一次登录
			JSONObject jsonObject = new JSONObject();
			if (null != user) {
				//已绑定
				if (StringUtils.isNotBlank(user.getPhone())) {
					jsonObject.put("isBind", true);
				} else {
					jsonObject.put("isBind", false);
				}
				//第一次登录
			} else {
				user = new User();
				user.setOpenId(openId);

				user.setNickname(userInfo.getNickname());
				user.setHeadPhoto(userInfo.getHeadPhoto());
				user.preInsert();
				baseMapper.insert(user);
				jsonObject.put("isBind", false);
			}
			//给用户jwt加密生成token
			String token = JWT.sign(user, 60L * 30L * 1000L);


			//封装成对象返回给客户端
			jsonObject.put("token", token);
			jsonObject.put("user", user);
			result.setData(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			result = TableResult.ErrorResult("认证失败");
		}
		return result;
	}
	@Override
	public String uploadObject(String title,
	                           MultipartFile mFile) {
		String fileId = "";
		System.out.println("title.isEmpty()="+title.isEmpty());
		//1.实现文件上传
		//1.1验证参数有效性
		if(title==null||title.trim().length()==0)
			throw new ServiceException("上传标题不能为空");
		if(mFile==null)
			throw new ServiceException("需要选择上传文件");
		if(mFile.isEmpty())
			throw new ServiceException("上传文件不能为空");

		//获得文件中的字节(应在文件上传之前)
		byte buf[]=null;
		try{
			buf=mFile.getBytes();
			String file64 = Base64.encodeToString(buf, 0);
			fileId = QiniuUploadFile.put64(file64);


			System.out.println("file的Id = "+fileId);
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException("文件摘要创建失败");
		}

		if(StringUtils.isBlank(fileId))
			throw new ServiceException("insert error");
		return fileId;
	}

}
